﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

using MySql.Data.MySqlClient;


namespace WpfApp2
{
    // 查询入参结构体
    public struct searchObj
    {
        public string name;
        public int age;
    };

    public partial class MainWindow : Window
    {

        // 查询入参
        

        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            string MyConStr = "Server=localhost;Database=aaa;uid=root;pwd=123456";

            MySqlConnection conn = new MySqlConnection(MyConStr);

            conn.Open();

            if (conn.State == ConnectionState.Open)
            {
                MessageBox.Show("Connection Opened Successfully");
                conn.Close();
            }
        }

        

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DBConnection conn = new DBConnection();
            // DataSet dataset = conn.Select();
            String name = nameText.Text;
            String age = ageText.Text;
            System.Diagnostics.Debug.WriteLine("输入数据:" + name + " " + age);
            searchObj obj;
            obj.name = name;
            if (age == string.Empty)
            {
                obj.age = -1;
            }
            else
            {
                obj.age = int.Parse(age);
            }

            DataTable dataset = conn.Select(obj);
            if (dataset == null)
            {
                MessageBox.Show("没有数据");
            }
            Console.WriteLine("查询到结果的行数:" + dataset.Rows.Count);
            for (var i = 0; i < dataset.Rows.Count; i++)
            {
                var row = dataset.Rows[i];
                var str = "";
                for (var j = 0; j < row.ItemArray.Length; j++)
                {
                    str += row[j] + "_";
                }
                Console.WriteLine("row：" + i + " " + str);
            }
            // https://blog.csdn.net/qq_37171353/article/details/78198415
            DataGrid1.ItemsSource = dataset.DefaultView;
            // 原文链接：https://blog.csdn.net/qq_43026206/article/details/86706431
        }

        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void Add_row(object sender, RoutedEventArgs e)
        {
            Window addDialog = new views.Window1();
            addDialog.Closed += AddDialog_Closed;
            addDialog.ShowDialog();
        }

        /// <summary>
        /// 获取一个类指定的属性值
        /// </summary>
        /// <param name="info">object对象</param>
        /// <param name="field">属性名称</param>
        /// <returns></returns>
        /// https://www.cnblogs.com/love201314/p/16730286.html
        public static object GetPropertyValue(object info, string field)
        {
            if (info == null) return null;
            Type t = info.GetType();
            IEnumerable<System.Reflection.PropertyInfo> property = from pi in t.GetProperties() where pi.Name.ToLower() == field.ToLower() select pi;
            return property.First().GetValue(info, null);
        }

        private void AddDialog_Closed(object sender, EventArgs e)
        {
            UserInfo u = (UserInfo)GetPropertyValue(sender, "DataContext");
            MessageBox.Show("你输入的是:"+u.user+"_"+u.age);
        }
    }

    class DBConnection
    {
        private MySqlConnection connection;
        private string connectionStr;

        public DBConnection()
        {
            try
            {
                string MyConStr = "Server=localhost;Database=web;uid=root;pwd=123456";
                /*connectionStr = ConfigurationManager.ConnectionStrings[MyConStr].ConnectionString;
                connection = new MySqlConnection(connectionStr);*/

                connection = new MySqlConnection(MyConStr);
            }
            catch (Exception exception)
            {
                throw new Exception("DBConnection Constructor:" + exception.Message);
            }
        }

        public DataTable Select(searchObj obj)
        {
            try
            {
                connection.Open();
                /*if (connection != null)
                {
                    connection.Open();
                }*/

                Console.WriteLine("---开始查询--");
                string cmdStr = "Select * from users";
                if (obj.name != "" && obj.age > -1)
                {
                    cmdStr = "Select * from users where name='" + obj.name + "' and age=" + obj.age;
                }
                else if (obj.name != "" && obj.age == -1)
                {
                    cmdStr = "Select * from users where name='" + obj.name + "'";
                }
                else if (obj.name == "" && obj.age > -1)
                {
                    cmdStr = "Select * from users where age=" + obj.age;
                }

                MySqlCommand sqlCmd = new MySqlCommand(cmdStr, connection);
                MySqlDataAdapter sda = new MySqlDataAdapter(sqlCmd);

                DataTable ds = new DataTable();
                sda.Fill(ds);
                return ds;
            }
            catch (Exception exception)
            {
                throw new Exception("SelectMethod:" + exception.Message);
            }
            finally
            {
                connection.Close();
            }
        }
    }
    // 原文链接：https://blog.csdn.net/qq_43026206/article/details/86706431
}
